if(!dojo._hasResource['vifito.galdic.DefinitionForm']){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource['vifito.galdic.DefinitionForm'] = true;

dojo.require('dojo.string');
dojo.require('dojo.dnd.Source');

dojo.provide('vifito.galdic.DefinitionForm');
dojo.declare("vifito.galdic.DefinitionForm", null, {
    
    idFactory: -1,
    
    dlgForm: null,
    domElement: null,
    dndSource: null,
    inputElement: null,
    values: [],
    baseurl: null,
    
    templateString: '',
    
    constructor: function(elem, dlg, options) {
        this.domElement = dojo.byId(elem);
        
        this.dndSource = new dojo.dnd.Source(elem);
        dojo.connect(this.dndSource, 'onDndDrop', this, this.orderOnDrop);
        
        this.dlgForm = dlg;
        dojo.connect(this.dlgForm, 'onCancel', this, this.resetForm);
        
        this.values = new Array();
        this.inputElement = options.inputElement || dojo.byId('json_definitions');
        
        this.baseurl = options.baseurl || '';
        this.templateString = options.templateString ||
        '<div id="${id}" category_id="${category_id}" etymology="${etymology}"> \
            <div class="content">${content}</div> \
            <div class="actions"> \
                <a href="#edit"><img src="'+this.baseurl+'/images/mini/edit.png" border="0" alt="" /></a> \
                <a href="#delete"><img src="'+this.baseurl+'/images/mini/delete.png" border="0" alt="" /></a> \
            </div> \
            <hr class="clearer" /> \
        </div>';
        
        this.enhanceUI();
        
        this.renderValues(options.values || []);            
    },
    
    enhanceUI: function() {
        // Pronuntiation button
        var button = dojo.create('button', {id: 'btnFonetic'});
        dojo.place(button, 'pronuntiation', 'after');
        
        var djBtn = new dijit.form.Button({label: '<img src="'+this.baseurl+'/images/mini/spread.png" /> Pronunciación'}, "btnFonetic");            
        dojo.connect(djBtn, 'onClick', function() {
            dijit.byId('dlgPronuntiation').show();
        });
        
        dijit.byId('submitbutton').setLabel('<img src="'+this.baseurl+'/images/mini/save.png" /> Gardar');
    },
    
    orderOnDrop: function () {
        var newValues = new Array();
        var elems = dojo.query('div[id]', this.domElement);
        
        for(var i=0; i<elems.length; i++) {
            newValues.push( this.getItem(elems[i].getAttribute('id')) );
        }
        
        this.values = new Array();
        this.values = newValues;
        this.updateValue();
    },
    
    generateId: function() {
        this.idFactory++;
        
        return 'df_' + this.idFactory;
    },
    
    renderValues: function(values) {
        this.domElement.innerHTML = '';
        dojo.forEach(values, dojo.hitch(this, 'addItem'));
        
        // Update input value
        this.updateValue();
    },
    
    addItem: function(data) {
        if(/^df_[0-9]+$/.test(data.id)) {
            this.updateItem(data);
        } else {
            this.values.push(data);
            this.renderItem(data);
            
            // Update input value
            this.updateValue();
        }                        
    },
    
    getItem: function(id) {
        for(var i=0; i<this.values.length; i++) {
            if(this.values[i].id == id) {
                return this.values[i];
            }                
        }
        
        return null;
    },
    
    renderItem: function(data) {
        data.id = this.generateId();
        
        var content = dojo.string.substitute(this.templateString, data);
        
        var element = dojo.create('li');
        dojo.addClass(element, 'dojoDndItem');
        element.innerHTML = content;                        
        
        this.domElement.appendChild(element);
        
        this.attachEvents(element);
        
        this.dndSource.insertNodes(false, [element]);
    },
    
    updateItem: function(data) {            
        var element = dojo.byId(data.id);            
        element.parentNode.innerHTML = dojo.string.substitute(this.templateString, data);
        
        this.attachEvents(element.parentNode);
        
        for(var i=0; i<this.values.length; i++) {
            if(this.values[i].id == data.id) {
                this.values[i] = data;
                return;
            }                
        }
        
        // Update input value
        this.updateValue();
    },
    
    attachEvents: function(element) {
        var links = dojo.query('div.actions a', element);            
        
        dojo.connect(links[0], 'onclick', this, this.onEditItem);
        dojo.connect(links[1], 'onclick', this, this.onRemoveItem);            
    },
    
    onEditItem: function(evt) {
        evt.stopPropagation();
        evt.preventDefault();
        
        var divElem = evt.currentTarget.parentNode.parentNode;
        
        if(divElem.nodeName == 'DIV') {
            var idItem = divElem.getAttribute('id');
            var data = this.getItem(idItem);
            
            if(data != null) {
                this.setValues(data);
                this.dlgForm.show();
            }                
        }                    
    },
    
    onRemoveItem: function(evt) {
        evt.stopPropagation();
        evt.preventDefault();
        
        var divElem = evt.currentTarget.parentNode.parentNode;
        
        if(divElem.nodeName == 'DIV') {
            var idItem = divElem.getAttribute('id');
            
            dojo.destroy( dojo.byId(idItem).parentNode ); // Destroy LI element 
            this.removeItem(idItem);
        }
    },
    
    removeItem: function(itemId) {
        var newValues = new Array();
        for(var i=0; i<this.values.length; i++) {
            if(this.values[i].id != itemId) {
                newValues.push(this.values[i]);
            }                
        }
        
        this.values = new Array();
        this.values = newValues;            
        
        // Update input value
        this.updateValue();
    },
    
    resetForm: function() {
        dijit.byId('content-Editor').setValue('');
        dijit.byId('category_id').setValue('0');
        dijit.byId('etymology').setValue('');
        dojo.byId('id_def').value = '';
    },
    
    setValues: function(data) {
        dojo.byId('id_def').value = data.id;
        dijit.byId('content-Editor').setValue(data.content);
        dijit.byId('category_id').setValue(data.category_id);            
        dijit.byId('etymology').setValue(data.etymology);            
    },
    
    updateValue: function() {
        this.inputElement.value = dojo.toJson(this.values);
    },
    
    attachDefinition: function() {
        var data = {};
        data.id = dojo.byId("id_def").value;
        data.etymology = dijit.byId("etymology").getValue();
        data.category_id = dijit.byId("category_id").getValue();
        data.content = dijit.byId("content-Editor").getValue();
        
        this.addItem(data);
        this.resetForm();
        
        this.dlgForm.hide();
    }
});

}
